import axios from 'axios'

let loading = null
let service_url = null
if (process.env.NODE_ENV === 'development') {
    service_url = '/url'
} else {
    service_url = '/'
}
const service = axios.create({
    baseURL: service_url,
    headers: {
        'Content-Type': 'application/json',
    },
    timeout: 30000,
})
// 发送请求前拦载
service.interceptors.request.use(
    (config) => {
        loading = ElLoading.service({
            lock: true,
            text: '数据加载中...',
            background: 'rgba(0, 0, 0, 0.2)',
        })
        config.headers['Access-Control-Allow-Origin'] = '*'
        // config.headers['Authorization'] = localStorage.getItem('Authorization') || ''
        let Authorization = ''
        let loc_ses = localStorage.getItem('loc_ses')
        // console.log('是否保持登录', loc_ses)
        if (loc_ses == 'true') {
            Authorization = localStorage.getItem('Authorization')
        } else {
            Authorization = sessionStorage.getItem('Authorization')
        }
        config.headers['Authorization'] = Authorization || ''
        // 默认参数
        var defaults = {}
        // 防止缓存，GET请求默认带_t参数
        if (config.method === 'get') {
            config.params = {
                ...config.params,
                ...{ _t: new Date().getTime() },
            }
        }
        return config
    },
    (error) => {
        loading.close()
        return Promise.reject(error)
    }
)

//发送请求返回拦载
service.interceptors.response.use(
    function (res) {
        loading.close()
        // 对响应数据做点什么
        var data = res.data
        // console.log('响应成功', data)
        if (data.code == 1) {
            return res.data
        } else if (data.code == -1) {
            loading.close()
            ElMessage({
                message: '登录失效,请重新登录',
                type: 'error',
            })
            localStorage.clear('Authorization') //删除
            setTimeout(function () {
                location.href = '/'
            }, 500)
            return res.data
        } else {
            // console.log('响应成功但是不正确', data)
            // alert('没有操作权限')
            // window.localStorage.clear('login') //删除
            // window.localStorage.clear('token') //删除
            // window.location.href = '/#/index'
            return res.data
        }
    },
    function (error) {
        loading.close()
        // 对响应错误做点什么
        console.log('响应失败', error)

        return error
    }
)

export default service
